//https://leetcode.cn/problems/binary-tree-preorder-traversal/description/

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
 /**
  * Note: The returned array must be malloced, assume caller calls free().
  */
void PreOrder(struct TreeNode* root, int* a, int* i)
{
    if (root == NULL)
    {
        return;
    }

    a[(*i)++] = root->val;
    PreOrder(root->left, a, i);
    PreOrder(root->right, a, i);

}

int TreeSize(struct TreeNode* root)
{
    return root == NULL ? 0 : TreeSize(root->left) + TreeSize(root->right) + 1;
}

int* preorderTraversal(struct TreeNode* root, int* returnSize) {
    *returnSize = TreeSize(root);
    int* a = (int*)malloc(sizeof(int) * (*returnSize));
    if (a == NULL)
    {
        perror("malloc fail\n");
        return NULL;
    }

    int i = 0;
    PreOrder(root, a, &i);

    return a;

}